package net.lesscoding.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;
import net.lesscoding.Const;

/**
 * @author eleven
 * @date 2024/10/23 14:51
 * @apiNote
 */
@Slf4j
public class ServerTest {

    public static void main(String[] args) {
        // 1. 启动器，负责组装netty组件，启动服务
        new ServerBootstrap()
                // 2. 添加事件循环组   BossEventLoop, WorkerEventLoop(selector, thread)
                .group(new NioEventLoopGroup())
                // 3. 选择服务器的ServerSocketChannel的实现类
                .channel(NioServerSocketChannel.class)
                // 4. boss处理链接请求 worker处理读写操作,
                // 4.1 ChannelInitializer 是一个特殊的handler，用于初始化channel 添加别的handler
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel channel) throws Exception {
                        channel.pipeline()
                                // 将 ByteBuf 转换成字符串
                                .addLast(new StringDecoder())
                                // 自定义handler, 处理业务逻辑
                                .addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                        log.debug("channel Read : {}", msg);
                                        super.channelRead(ctx, msg);
                                    }
                                })
                        ;
                    }
                })
                // 5. 绑定端口
                .bind(Const.PORT)
        ;
    }
}
